using System;

namespace DelegateAndEventExample // 命名空间
{
    // 声明一个委托
    public delegate void Notify(string message);

    // 定义一个发布者类
    public class Publisher
    {
        // 声明事件
        public event Notify OnNotify;

        public void DoSomething()
        {
            Console.WriteLine("Publisher is doing something...");
            // 触发事件
            NotifyObservers("Something has happened!");
        }

        protected virtual void NotifyObservers(string message)
        {
            // 检查事件是否有订阅者
            if (OnNotify != null)
            {
                OnNotify(message); // 触发事件通知所有订阅者
            }
        }
    }

    // 定义一个订阅者类
    public class Subscriber
    {
        public void Subscribe(Publisher publisher)
        {
            // 订阅事件
            publisher.OnNotify += HandleNotification;
        }

        // 事件处理方法
        private void HandleNotification(string message)
        {
            Console.WriteLine($"Subscriber received notification: {message}");
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            Subscriber subscriber = new Subscriber();

            // 订阅事件
            subscriber.Subscribe(publisher);

            // 发布者执行某个操作
            publisher.DoSomething();
        }
    }
}
